<?php

namespace App\Http\Controllers\Api;

use App\Http\Transformers\PurchaseTransformer;
use App\Models\Purchase;
use App\Models\Product;
use App\Models\User;
use App\Models\CouponNumber;
use App\Models\Coupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;

class PurchasesController extends BaseController
{
    /**
     * 订单列表
     */
    public function index(Request $request)
    {
        $user = $this->current_user();
        if (empty($user->id)) {
            return responseMsg(false, '用户不存在');
        }
        $purchases = Purchase::productType()->where('user_id', $user->id)->orderBy('created_at', 'desc')->paginate(15);
        $is_seller = false;
        if ($request->input('is_seller')) {
            $is_seller = true;
        }
        $returnArr = PurchaseTransformer::purchase_list($purchases, $is_seller);
        return responseMsg(true, '', $returnArr, $purchases->lastPage());
    }

    /**
     * 下订单
     */
    public function store(Request $request)
    {
        try {
            $params = $this->_params($request);
            \DB::beginTransaction();
			\Log::info($params);
            $purchase = new Purchase($params);
            $purchase->save();
            \DB::commit();
            return responseMsg(true, '订单提交成功', PurchaseTransformer::purchase($purchase));
        } catch (\Exception $e) {
            \DB::rollback();
            \Log::info($e, ['purchase store error']);
            return responseMsg(false, $e->getMessage());
        }
    }

    /**
     * 订单详情
     * @param $id
     */
    public function show(Request $request, $id)
    {
        $user = $this->current_user();
        if (empty($user->id)) {
            return responseMsg(false, '用户不存在');
        }
        $purchase = Purchase::find($id);
        $is_seller = false;
        if (!$purchase) {
            return responseMsg(false, '订单不存在');
        }
        if ($request->input('is_seller') || $user->id == $purchase->seller_user_id) {
            $is_seller = true;
        }
        $purchase->total = $purchase->total();
        $purchase->save();
        $purchase = PurchaseTransformer::purchase($purchase, $is_seller);

        return responseMsg(true, '', $purchase);
    }

    /**
     * 更新订单
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        $user = $this->current_user();
        if(empty($user->id)){
            return responseMsg(false,'用户不存在');
        }
        $status = $request->input('status');
        if (!$status) {
            return responseMsg(false, '订单状态不正确');
        }
        $flag = false;
        $message = '订单状态异常';
        try {
            $key = 'purchase_update:' . $user->id . ':' . $id;
            if (Redis::exists($key)) {
                throw new \Exception('操作太频繁');
            }
            Redis::set($key, 'purchase');
            Redis::expire($key, 2);
            \DB::beginTransaction();
            $purchase = Purchase::where('id', $id)->lockForUpdate()->first();
            if (!$purchase) {
                return responseMsg(false, '订单不存在');
            }
            //确认完成订单
            if ($status == 'finish') {
                $flag = $purchase->purchase_finish();
            }
            //同意订单
            if ($status == 'accept') {
                $flag = $purchase->purchase_accept();
            }
            //拒绝订单
            if ($status == 'reject') {
                $flag = $purchase->purchase_reject();
            }
            if ($flag) {
                $message = '操作成功';
                \DB::commit();
            }
        } catch (\Exception $e) {
            \DB::rollback();
			\Log::error($e);
            return responseMsg(false, $e->getMessage());
        }
        return responseMsg($flag, $message);
    }

    /**
     * 删除订单
     * @param $id
     */
    public function destroy($id)
    {
        $user = $this->current_user();
        if (empty($user->id)) {
            return responseMsg(false, '用户不存在');
        }
        $purchase = Purchase::find($id);
        if (!$purchase) {
            return responseMsg(false, '订单不存在');
        }
        if ($purchase->user_id != $user->id) {
            return responseMsg(false, '非法请求');
        }
        if (in_array($purchase->status_str(), ['ACCEPT_WAITING', 'ACCEPT'])) {
            return responseMsg(false, '无法删除');
        }
        if ($purchase->is_payed == Purchase::PAY_WAITING) {
            $purchase->status = Purchase::STATUS_BUYER_CANCEL;
            $purchase->save();
        }

        $purchase->delete();

        return responseMsg(true, '订单删除成功');
    }

    /**
     * 获取订单参数
     * @param Request $request
     * @return array
     */
    private function _params(Request $request)
    {
        $user = $this->current_user();
        if (empty($user->id)) {
            $wx_user = Session::get('wx_user');
            if ($wx_user) {
                $user = User::find($wx_user->user_id);
            } else {
                throw(new \Exception('用户不存在'));
            }
        }
        $key = 'purchase:' . $user->id . ':' . $request->input('product_id');
        if (Redis::exists($key)) {
            throw new \Exception('一个服务30秒内只能购买一次');
        }
        Redis::set($key, 'purchase');
        Redis::expire($key, 30);
        $product = Product::find($request->input('product_id'));
        if (!$product) {
            throw(new \Exception('商品不存在'));
        }
        $server_date = $request->input('server_date');
        if (!$server_date || strtotime($server_date) < time()) {
            throw(new \Exception('服务时间不正确'));
        }

        $coupon_number_id = intval($request->input('coupon_number_id'));
        $total = $request->input('total');
        if($coupon_number_id>0)
        {
            $coupon_number = CouponNumber::find($coupon_number_id);
            if(!empty($coupon_number))
            {
                $coupon_id = $coupon_number->coupon_id;
                $coupon =  Coupon::find($coupon_id);
                if(!empty($coupon))
                {
                   $order_scope =  $coupon->order_scope;
                   if($total<$order_scope)
                   {
                       throw(new \Exception('优惠券不可用01'));
                   }

                }

            }

        }

        $arr = array(
            'user_id' => $user->id,
            'product_id' => $request->input('product_id'),
            'server_date' => $server_date,
            'coupon_number_id' => $request->input('coupon_number_id'),
            'count' => $request->input('count', 1),
            'pay_method' => $request->input('pay_method', ''),
            'seller_user_id' => $product->user_id,
            'type' => $product->model_name(),
            'unread' => 2,
            'total' => 0
        );

        if ($request->input('source')) {
            $arr['source'] = $request->input('source');
        }
        if ($request->input('total')) {
            $arr['total'] = $request->input('total');
        }

        return $arr;
    }
}
